package com.bamboo.common.utils;

import com.google.common.base.Converter;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Constructor;
import java.util.Objects;


/**
 * @author : bamboo
 * @date : 2020-04-03
 */
public class DTOConverter<S, T> extends Converter<S, T> {
    private S s1;
    private T t1;

    public DTOConverter(Class<?> source, Class<?> target) {
        try {
            if (Objects.nonNull(source)) {
                try {
                    s1 = (S) source.newInstance();
                } catch (Exception e) {
                }
                if (Objects.isNull(s1)) {
                    Constructor<?>[] declaredConstructors = source.getDeclaredConstructors();
                    Constructor<?> declaredConstructor = declaredConstructors[0];
                    declaredConstructor.setAccessible(true);
                    s1 = (S) declaredConstructor.newInstance();
                }
            }

            if (Objects.nonNull(target)) {
                try {
                    t1 = (T) target.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (Objects.isNull(t1)) {
                    Constructor<?>[] declaredConstructors = target.getDeclaredConstructors();
                    Constructor<?> declaredConstructor = declaredConstructors[0];
                    declaredConstructor.setAccessible(true);
                    t1 = (T) declaredConstructor.newInstance();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected T doForward(S s) {
        BeanUtils.copyProperties(s, t1);
        return t1;
    }

    @Override
    protected S doBackward(T t) {
        BeanUtils.copyProperties(t, s1);
        return s1;
    }
}
